package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSONObject;
import com.lark.oapi.Client;
import com.lark.oapi.core.request.RequestOptions;
import com.lark.oapi.core.utils.Jsons;
import com.lark.oapi.service.authen.v1.model.CreateAccessTokenReq;
import com.lark.oapi.service.authen.v1.model.CreateAccessTokenReqBody;
import com.lark.oapi.service.authen.v1.model.CreateAccessTokenResp;
import com.lark.oapi.service.authen.v1.model.GetUserInfoResp;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FeishuOfficeUtil implements InitializingBean {

    /*飞书-BI*/
    @Value("${feishu.bi.appid}")
    private String bi_appid;
    @Value("${feishu.bi.appsectet}")
    private String bi_appsectet;
    static String bi_APPID;
    static String bi_APPSECTET;
    /*飞书-BI*/

    @Override
    public void afterPropertiesSet(){
        bi_APPID = bi_appid;
        bi_APPSECTET = bi_appsectet;
        System.err.println("飞书配置文件类初始化");
    }

    /**
     * 免登录
     * @throws Exception
     */
    public static String singleLogin(String code) throws Exception {
        Client client = Client.newBuilder(bi_APPID, bi_APPSECTET).build();
        CreateAccessTokenReq req = CreateAccessTokenReq.newBuilder()
                    .createAccessTokenReqBody(CreateAccessTokenReqBody.newBuilder()
                    .grantType("authorization_code")
                    .code(code)
                    .build())
                .build();

        CreateAccessTokenResp tokenResp = client.authen().accessToken().create(req);

        JSONObject tokenJson = JSONObject.parseObject(Jsons.DEFAULT.toJson(tokenResp.getData()));
        String token = tokenJson.getString("access_token");

        return token;
    }
    public static GetUserInfoResp getUserInfoResp(String token) throws Exception {
        Client client = Client.newBuilder(bi_APPID, bi_APPSECTET).build();
        GetUserInfoResp resp = client.authen().userInfo().get(RequestOptions.newBuilder()
                .userAccessToken(token)
                .build());
        System.out.println(Jsons.DEFAULT.toJson(resp.getData()));
        return resp;
    }

    public static void main(String[] args) throws Exception {

    }
}
